/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Robot;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import lejos.nxt.LCD;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;

/**
 *
 * @author zach
 */
public class Comm extends Thread{
    private String waiting="main screen turn on.";
    private String connected="we get signal";
    private String closing="someone set us up the bomb";
    private BTConnection conn;
    private DataInputStream in;
    private DataOutputStream out;
    private boolean isInterupted=false;
    private static Map<String,Command> commands_list=new Map<String,Command>();
    private String[] commands;
    public Comm() {
        LCD.drawString(waiting, 0, 0);
        conn = Bluetooth.waitForConnection();

        LCD.clear();
        LCD.drawString(connected, 0, 0);

        in=conn.openDataInputStream();
        out=conn.openDataOutputStream();

        commands=new String[commands_list.keySet().size()];
        int z=0;
        for(String i:commands_list.keySet()){
            commands[z]=i;
            z++;
        }
    }

    @Override
    public void interrupt() {
        try {
            isInterupted = true;
            LCD.drawString(closing, 0, 0);
            in.close();
            out.close();
            conn.close();
        } catch (IOException ex) {
            System.err.println(ex);
        }


    }

    @Override
    public boolean isInterrupted() {
        return isInterupted;
    }

    @Override
    public void run() {
        while(!interrupted()){
            try {
                int command_number = in.readInt();
                double command_data=in.readDouble();
                String zig=commands_list.get(commands[command_number]).exec(command_data);
                for(char i:zig.toCharArray())
                    out.write(i);
                out.flush();
            } catch (IOException ex) {
                System.err.println(ex);
            }

        }
    }
    public void loadCommands(Map<String,Command> in){
        commands_list.putAll(in);
        int z=0;
        for(String i:commands_list.keySet()){
            commands[z]=i;
            z++;
        }
    }
}
